import axios from 'axios'
import qs from 'qs'
import router from '../router'
import store from '../store'

let baseUrl = process.env.VUE_APP_BASEURL;

axios.interceptors.request.use(function (conf) {
    return conf;
}, function (error) {
    // 抛出请求错误信息
    Promise.reject(error.response);
}); // 添加响应拦截器

axios.interceptors.response.use(function (response) {
    if (response.data === '') {
        return Promise.reject({
            "msg": "数据接口发生错误,请稍后重试"
        });
    }
    //token失效时返回
    if (response.data.codeId) {
        //商户token失效时返回
        if (response.data.codeId == -99) {
            router.replace("/login");
            return Promise.reject(response.data);
        }
        //非200时即为错误
        if (response.data.codeId != 200) {
            return Promise.reject(response.data);
        }
        return response.data;
    } else {
        return response;
    }
}, function (error) {
    // 请求失败处理
    console.log(error);
    return Promise.reject(error);
});

const getData = function getData(url, params) {
    return new Promise(function (resolve, reject) {
        axios.get(baseUrl + url, {
            params,
            headers: {
                token: store.state.userInfo.token || ''
            }
        }).then(function (res) {
            resolve(res);
        }).catch(function (err) {
            reject(err);
        });
    });
};
const postData = function postData(url, params) {
    return new Promise(function (resolve, reject) {

        axios.post(baseUrl + url, {
            ...params,
        }, {
            headers: {
                token: store.state.userInfo.token || ''
            }
        }
        ).then(function (res) {
            resolve(res);
        }).catch(function (err) {
            reject(err);
        });
    });
};
const post2Data = function postData(url, params) {
    return new Promise(function (resolve, reject) {

        axios.post(baseUrl + url, params, {
            headers: {
                token: store.state.userInfo.token || ''
            }
        }
        ).then(function (res) {
            resolve(res);
        }).catch(function (err) {
            reject(err);
        });
    });
};
const postFormData = function postData(url, params) {
    return new Promise(function (resolve, reject) {
        let formData = new FormData();
        formData.append('token', store.state.userInfo.token || '');
        for (let key in params) {
            formData.append(key, params[key]);
        }
        formData.append('platform', 'web');
        axios.post(baseUrl + url, formData).then(function (res) {
            resolve(res);
        }).catch(function (err) {
            console.log(err)
            reject(err);
        });
    });
};
function downloadFile(data, type, fileName) {
    let blob = new Blob([data], { type: `${type}` });
    // 获取heads中的filename文件名
    let downloadElement = document.createElement('a');
    // 创建下载的链接
    let href = window.URL.createObjectURL(blob);
    downloadElement.href = href;
    // 下载后文件名
    downloadElement.download = fileName;
    document.body.appendChild(downloadElement);
    // 点击下载
    downloadElement.click();
    // 下载完成移除元素
    document.body.removeChild(downloadElement);
    // 释放掉blob对象
    window.URL.revokeObjectURL(href);
}
const getFileData = function getData(url, params) {
    return new Promise(function (resolve, reject) {
        params = {
            ...params, token: store.state.userInfo.token || ''
        }

        axios({ type: 'GET', url: baseUrl + url, params: params,headers: {
            token: store.state.userInfo.token || ''
        }, responseType: "arraybuffer" }).then(function (res) {
            try {
                //如果JSON.parse(enc.decode(new Uint8Array(res.data)))不报错，说明后台返回的是json对象，则弹框提示
                //如果JSON.parse(enc.decode(new Uint8Array(res.data)))报错，说明返回的是文件流，进入catch，下载文件
                let enc = new TextDecoder('utf-8')
                res = JSON.parse(enc.decode(new Uint8Array(res.data))) //转化成json对象
                if (res.codeId == -99) {
                    router.replace("/login");
                    reject(res);
                }
            } catch (err) {
                const data = res.data;
                const content = res.headers['content-disposition'];
                const type = res.headers['content-type'];
                const fileName = decodeURIComponent((content && content.split(';')[1].split('filename=')[1])) || '导出列表.xls';
                downloadFile(data, type, fileName)
                resolve(res);
            }
        }).catch(function (err) {
            reject(err);
        });
    });
};
export default { baseUrl, getData, postData,post2Data, postFormData, getFileData }